package com.my.api.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.my.api.request.AppRequestHead;
import com.my.api.response.Msg;
import com.my.util.JWTUtil;
import com.my.util.RequestUtil;

public class AuthenticationInterceptor implements HandlerInterceptor{
	
	@Autowired
	private JWTUtil jwtUtil;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
		//获取请求的方法
		String currentURL = request.getRequestURI(); // 取得根目录所对应的绝对路径: 
		int index = currentURL.indexOf('/', 1);
		if(index > 0) {
			String targetURL = currentURL.substring(index,currentURL.length()); // 截取到当前路径名用于比较  
			if(targetURL.startsWith("/v1/")){
				AppRequestHead appRequestHead = RequestUtil.convertToAppRequestHead(request);
				if(appRequestHead == null){
					RequestUtil.responseOutWithJson(response, new Msg(Boolean.FALSE, 100, "系统参数不能为空"));
					return false;
				}else{
					if(!jwtUtil.checkToken( appRequestHead.getToken())){
						RequestUtil.responseOutWithJson(response, new Msg(Boolean.FALSE, 999, "token失效"));
						return false;
					}
				}
			}
		}
		return true;
	}
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)throws Exception {
		
	}

}
